package com.teach.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teach.config.RabbitmqConfig;
import com.teach.dto.ResponseEntityDto;

import com.teach.dto.TbCreateOrderDto;
import com.teach.entity.TbCourseBase;
import com.teach.entity.TbOrder;
import com.teach.mapper.TbOrderMapper;
import com.teach.service.TbOrderService;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 *
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    TbOrderService tbOrderService;

    Logger logger = LogManager.getLogger(TbOrderServiceImpl.class);//实例log日志对象

    /**
     *
     * @param tbCourseBase 生成课程订单dto
     * @param token 个人信息
     * @return
     */
    @Override
    @Transactional
    public ResponseEntityDto createorder(TbCreateOrderDto tbCourseBase, String token) {
        try {
            //解析token
            String uid = (String) Jwts.parser()
                    .setSigningKey("luosz")
                    .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxIn0.6aWCr4Hd6g-I8zumggyPqM_ZGaAAVXpyv-64RfHbR_s")
                    .getBody()
                    .get("uid");


            //uuid生成订单号
            UUID uuid = UUID.randomUUID();


            TbOrder tbOrder =new TbOrder()//生成订单
                    .setName(tbCourseBase.getCourseName())
                    .setOrderNumber(uuid+"")
                    .setPrice(tbCourseBase.getCoursePrice().longValue()-tbCourseBase.getCourseDiscounts().longValue())
                    .setUserId(Integer.valueOf(uid))
                    .setCourseId(tbCourseBase.getId())
                    .setPayState(1);
            //更新数据库
            tbOrderService.save(tbOrder);


            /**
             * * 发送端代码 *
             * @param message 消息数据 *
             * @param ttlesg  过期时间 *
             * @return */
            //发送mq队列
            rabbitTemplate.convertAndSend(
                    RabbitmqConfig.DELAY_EXCHANGE,//找到交换机
                    RabbitmqConfig.DELAY_MESSAGE_KEY,//找到routingkey
                    tbOrder.getId(),//发送订单id
                    messg ->{
                        messg.getMessageProperties().setDelay(60000);//设置时间为1分钟 单位 毫秒
                        return messg;
                    });

            return new ResponseEntityDto(null,2000,"成功",true);
        } catch (ExpiredJwtException e) {
            logger.error("生成订单异常为"+e.getMessage());
            return new ResponseEntityDto(null,5000,"异常"+e.getMessage(),false);
        }
    }
}




